package com.yuan.springcloud.user.controller;

import cn.hutool.core.io.resource.MultiFileResource;
import cn.hutool.core.io.resource.Resource;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.yuan.springcloud.common.web.bean.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author YouYuan
 * @date 2021/1/28 22:37
 */
@Api(value = "文件接口",tags = "文件")
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController extends BaseController {

    @ApiOperation(value = "转发文件",notes = "接收文件并转发到其他服务")
    @PostMapping("/forwardFile")
    public Result forwardFile(@RequestParam("files") MultipartFile[] files, @RequestParam("remark") String rem) throws IOException {
        log.info("forwardFile files:{}, rem:{}", files, rem);
        if (files != null && files.length > 0) {
            File[] fileArr = new File[files.length];
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
                File tempFile = new File("E:\\Temp\\Upload\\Temp\\forwardFile-" + file.getOriginalFilename());
                file.transferTo(tempFile);
                fileArr[i] = tempFile;
            }
            HttpResponse response = HttpRequest.post("http://localhost:9080/file/uploadFile")
                    .form("files", fileArr)
                    .form("remark", "f:" + rem)
                    .execute();
            log.info(response.body());
            return Result.success(response.body());
        }
        return Result.success();
    }

    @ApiOperation(value = "上传文件",notes = "上传文件")
    @PostMapping("/uploadFile")
    public Result uploadFile(@RequestParam("files") MultipartFile[] files, @RequestParam("remark") String remark) throws IOException {
        log.info("uploadFile files:{}, remark:{}", files, remark);
        if (files != null && files.length > 0) {
            for (MultipartFile file : files) {
                file.transferTo(new File("E:\\Temp\\Upload\\Temp\\upload-" + file.getOriginalFilename()));
            }
        }
        return Result.success();
    }
}
